import type { IQueue, IStructureItem } from '../type'

/**
 * @author hzq
 * @description 队列
 * @date 2024-11-03
 */
class Queue<T> implements IQueue<T> {
  private items: IStructureItem<T>
  private count: number
  private header: number
  constructor() {
    this.items = {}
    this.count = this.header = 0
  }
  enqueue(item: T): number {
    this.items[this.count++] = item
    return this.count
  }
  dequeue(): T | undefined {
    if (this.isEmpty()) return void 0
    const result = this.items[this.header]
    delete this.items[this.header++]
    return result
  }
  font(): T | undefined {
    if (this.isEmpty()) return void 0
    return this.items[this.header]
  }
  isEmpty(): boolean {
    return this.size === 0
  }
  clear(): void {
    this.items = {}
    this.count = this.header = 0
  }
  get size(): number {
    return this.count - this.header
  }

  toString(): string {
    if (this.isEmpty()) return 'queue is empty!'
    //@ts-ignore
    let result = this.items[this.header].toString()
    for (let i = this.header + 1; i < this.count; i++) {
      //@ts-ignore
      result = `${result},${this.items[i].toString()}`
    }
    return result
  }
}

export default Queue
